package teamblue.cardex.activities;

import teamblue.cardex.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.ByteMatrix;

import android.os.Bundle;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Matrix;
import android.util.Log;
import android.widget.ImageView;
import android.app.Dialog;
import android.content.Context;

public class BarcodeDialog extends Dialog{
	
	private BarcodeFormat format;
	private String data;
	private int width;
	private int height;
	
	public BarcodeDialog(Context context,BarcodeFormat format,String data,int width,int height)
	{
		super(context);
		this.format=format;
		this.data=data;
		//we switch these so that the barcode fills the screen vertically
		this.width=height;
		this.height=width;
	}
	
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.barcode);
		
		setTitle(data);
		ImageView barcode=(ImageView)findViewById(R.id.barcode_image);
		
		MultiFormatWriter writer=new MultiFormatWriter();
    	try
    	{
    		ByteMatrix result=writer.encode(data, format, width, height);
            byte[][] array = result.getArray();
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
              for (int x = 0; x < width; x++) {
                int grey = array[y][x] & 0xff;
                // pixels[y * width + x] = (0xff << 24) | (grey << 16) | (grey << 8) | grey;
                pixels[y * width + x] = 0xff000000 | (0x00010101 * grey);
              }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            
            //rotate the barcode
            if(format!=BarcodeFormat.UPC_A && format!=BarcodeFormat.UPC_E && format!=BarcodeFormat.EAN_13 && format!=BarcodeFormat.EAN_8)
            {
            	Matrix matrix=new Matrix();
            	matrix.postRotate(90);
            	bitmap=Bitmap.createBitmap(bitmap,0,0,width,height,matrix,false);
            }
            
            BitmapDrawable bmd = new BitmapDrawable(bitmap);
            barcode.setImageDrawable(bmd);
    	}
    	catch(Exception e)
    	{
    		Log.e("ERROR",""+e);
    	}
	}
}